package stage1.operation.module4.chat;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

//发送信息线程
class SendClientThreat implements Runnable {
    Socket socket;
    PrintWriter pWriter;
    Scanner scanner;

    public SendClientThreat(Socket socket) {
        super();
        this.socket = socket;
        this.scanner = new Scanner(System.in);
        try {
            pWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            String msg = scanner.nextLine();
            File file = new File(msg);
            // 文件传输有点麻烦，后面再完善吧
            if (file.isFile()){
                try {
                    FileInputStream fis = new FileInputStream(file);
                    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                    dos.flush();
                    dos.flush();
                    // 开始传输文件
                    byte[] bytes = new byte[1024];
                    int length = 0;
                    long progress = 0;
                    while((length = fis.read(bytes, 0, bytes.length)) != -1) {
                        dos.write(bytes, 0, length);
                        dos.flush();
                        progress += length;
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String strMsg = msg;
            pWriter.println(socket.getRemoteSocketAddress() +"发送的消息是："+strMsg);
            pWriter.flush();
        }
    }
}
